題目:
Given an input string s and a pattern p, implement regular expression matching with support for '.' and '*' where:
'.' Matches any single character.
'' Matches zero or more of the preceding element.
The matching should cover the entire input string (not partial).
給定一個輸入字串s 和一個模式p,實現支援和的正則表達式匹配,'.'其中'':
題目要求
給定字串 s 和模式 p,實現 isMatch(s, p),回傳 true 或 false,判斷是否完全匹配。
'.'匹配任意單一字元。
'*'匹配零個或多個前一個元素。
匹配應該覆蓋整個輸入字串(而不是部分)
解題思路
這題的關鍵是 動態規劃 (DP):
定義狀態
設 dp[i][j] 表示字串 s[0..i-1] 與模式 p[0..j-1] 是否匹配。
初始條件
dp[0][0] = true(空字串匹配空模式)。
若模式含有 *,必須判斷是否能匹配空字串。
狀態轉移
如果 p[j-1] 是普通字元或 .:
dp[i][j] = dp[i-1][j-1] && (s[i-1] == p[j-1] 或 p[j-1] == '.')
如果 p[j-1] == '*':
看前一個字元 p[j-2]:
0 次:忽略這兩個字元 → dp[i][j] = dp[i][j-2]
1 次以上:如果 s[i-1] 能和 p[j-2] 匹配 → dp[i][j] = dp[i-1][j]
答案
最終回傳 dp[m][n],其中 m = s 長度,n = p 長度。